import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sports_new/controller/live/qkd_player_logic.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/get_icon.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/home/inner_video/inner_video.dart';
import 'package:sports_new/view/match_detail/live/live_loading.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:volume_controller/volume_controller.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../match_detail/live/match_live_view.dart';
import '../video/video_speed_bottomsheet.dart';

class InnerVideoPanel extends StatefulWidget {
  final ExtensionContext context;
  final QkdPlayerLogic logic;

  const InnerVideoPanel({
    super.key,
    required this.context, required this.logic
  });

  @override
  State<InnerVideoPanel> createState() => _InnerVideoPanelState();
}

class _InnerVideoPanelState extends State<InnerVideoPanel> {
  QkdPlayerLogic get player => widget.logic;

  Timer? _hideTimer;
  bool _hideStuff = true;
  final double barHeight = 72;

  @override
  void initState() {
    super.initState();
    _cancelAndRestartTimer();
  }

  @override
  void didChangeDependencies() {
    player.addListener(() {
      if(mounted) {
        setState(() {});
      }
    });
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    super.dispose();
    _hideTimer?.cancel();
  }

  void _startHideTimer() {
    _hideTimer?.cancel();
    _hideTimer = Timer(const Duration(seconds: 3), () {
      setState(() {
        _hideStuff = true;
      });
    });
  }

  void _playOrPause() {
    if (player.status == PlayStatus.started) {
      player.pause();
    } else if(player.status == PlayStatus.paused){
      player.pauseToPlay();
    }else if(player.status == PlayStatus.idle){
      player.play();
    }else{
      player.doRefresh();
    }
  }

  void changeOrientation() async {
    if(MediaQuery.of(Get.context!).orientation == Orientation.landscape){
      await SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitUp,DeviceOrientation.portraitDown]
      );
      await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
      await Future.delayed(
          const Duration(microseconds: 300)
      ).then((value) => Get.back());
    }else{
      MaterialPageRoute<MatchLiveView> page = MaterialPageRoute(
        builder: (context)=> InnerVideoWidget(
          extensionContext: widget.context,
          logic: player,
        )
      );
      SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft,DeviceOrientation.landscapeRight]
      );
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
      await Future.delayed(const Duration(milliseconds: 200));
      await navigator?.push(page);
    }
  }

  void _cancelAndRestartTimer() {
    if (_hideStuff == true) {
      _startHideTimer();
    }
    setState(() {
      _hideStuff = !_hideStuff;
    });
  }

  AnimatedOpacity _buildTopBar(BuildContext context) {
    return AnimatedOpacity(
      opacity: _hideStuff ? 0.0 : 1,
      duration: const Duration(milliseconds: 400),
      child: Container(
        height: barHeight,
        padding: EdgeInsets.only(top: MediaQuery.of(Get.context!).orientation == Orientation.landscape?10:0, left: 10),
        decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Colours.black.withOpacity(0.8),Colors.transparent],
                begin: Alignment.topCenter,end: Alignment.bottomCenter
            )
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: 40,
              child: Row(
                children: [
                  if(Get.mediaQuery.orientation == Orientation.landscape)...[
                    IconButton(
                      onPressed: changeOrientation,
                      icon: Image.asset(
                        Utils.getImgPath('arrow_back.png'),
                        color: Colours.white,
                        width: 24,
                        height: 24,
                      ),
                    ),
                    QkdText(
                      '${Get.previousRoute.contains(Routes.viewpoint)?"观点":"资讯"}详情',
                      fontSize: 16,
                      color: Colours.white,
                    ),
                  ],
                  const Spacer(),
                  QkdButton(
                    height: 30,
                    width: 50,
                    onPressed: () async {
                      double? changeSpeed =
                      await Get.bottomSheet(VideoSpeedBottomsheet(await player.player.getRate()));
                      if (changeSpeed != null) {
                        player.player.setRate(changeSpeed);
                      }
                    },
                    text: '倍速',
                    textStyle: const TextStyle(fontSize: 12, color: Colours.white),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  AnimatedOpacity _buildBottomBar(BuildContext context) {
    return AnimatedOpacity(
      opacity: _hideStuff ? 0.0 : 1,
      duration: const Duration(milliseconds: 400),
      child: Container(
        height: barHeight,
        padding: EdgeInsets.only(bottom: MediaQuery.of(Get.context!).orientation == Orientation.landscape?10:0),
        decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Colours.black.withOpacity(0.8),Colors.transparent],
                begin: Alignment.bottomCenter,end: Alignment.topCenter
            )
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            SizedBox(
              height: 40,
              child: Row(
                children: <Widget>[
                  IconButton(
                      onPressed: _playOrPause,
                      icon: Icon(
                        player.status == PlayStatus.paused?
                        GetIcon.pause:GetIcon.play,
                        color: Colours.white,
                        size: 24,
                      )
                  ),
                  QkdText(player.startSlide?player.formTime():player.positionTime,fontSize: 12,color: Colours.white),
                  Container(width: 4),
                  Expanded(child: slider()),
                  Container(width: 4),
                  QkdText(player.totalTime,fontSize: 12,color: Colours.white),
                  GestureDetector(
                    onTap: changeOrientation,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      child: Image.asset(
                        Utils.getImgPath('fullscreen_icon.png'),
                        // color: Colours.text,
                        width: 24,
                      ),
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return player.status == PlayStatus.idle || player.status == PlayStatus.completion?
    Center(
        child: GestureDetector(
            onTap: player.play,
            child: Image.asset(
                Utils.getImgPath('video_play.png'),
                width: 50,height: 50
            )
        )
    ):GestureDetector(
      onTap: _cancelAndRestartTimer,
      onHorizontalDragStart: (details){
        player.startSlide = true;
        player.onSlide = true;
        player.slidePosition = player.currentPosition.toDouble();
      },
      onHorizontalDragUpdate: (details){
        Logger().d("${details.delta.dx/Get.width * 60000} 当前时长：${player.formTime()} 总时长：${player.totalTime}");
        player.slidePosition += details.delta.dx/Get.width * 60000;
      },
      onHorizontalDragEnd: (details) {
        player.setPosition();
      },
      // onVerticalDragUpdate: (DragUpdateDetails details) async {
      //   if(details.globalPosition.dy < 40) return;
      //   if (startOffset.dx > Get.width*5/8) {
      //     var offset = details.delta - startOffset;
      //     if(oldOffset.dy.abs() > offset.dy.abs()) startOffset = details.globalPosition;
      //     offset = details.globalPosition - startOffset;
      //     player.onVolumnChanged(offset);
      //     oldOffset = offset;
      //   } else if(startOffset.dx < Get.width*3/8){
      //     player.onBrightnessChanged(details.globalPosition - startOffset);
      //   }
      // },
      behavior: HitTestBehavior.opaque,
      child: Stack(
        alignment: AlignmentDirectional.center,
        children: [
          if(player.status == PlayStatus.prepared || player.status == PlayStatus.initialized)...[
            Image.asset(
                width: Get.width,
                fit: BoxFit.cover,
                Utils.getImgPath("live_back.png")
            ),
            const Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                LiveLoading(
                  color: Colours.white,
                  size: 44,
                ),
                QkdText("加载中",color: Colours.white)
              ],
            )
          ]
          else if(player.status == PlayStatus.error)...[
            Image.asset(
                width: Get.width,
                fit: BoxFit.cover,
                Utils.getImgPath("live_back.png")
            ),
            Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const QkdText("视频加载失败，请稍后重试",color: Colours.white),
                Container(height: 8),
                QkdButton(
                    onPressed: player.doRefresh,
                    text: "重新连接",
                    width: 74,height: 30,
                    borderRadius: 6,
                    foregroundColor: Colours.main,
                    borderSide: const BorderSide(color: Colours.main,width: 0.5)
                )
              ],
            )
          ]else if(player.status == PlayStatus.completion)...[
            // Image.asset(
            //     width: Get.width,
            //     fit: BoxFit.cover,
            //     Utils.getImgPath("live_back.png")
            // ),
            // const QkdText("视频放完啦，看看其他的吧～",color: Colours.white)
          ],
          if(player.status == PlayStatus.stopped)...[

          ],
          if(player.startSlide)
            Positioned.fill(
              child: Container(
                  color: Colours.black.withOpacity(0.8),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          QkdText(
                            player.formTime(),
                            fontSize: 20,
                            color: Colours.main,
                            needCenter: true,
                          ),
                          Container(width: 4),
                          QkdText("/${player.totalTime}",
                            color: Colours.white,
                            needCenter: true,
                          ).paddingOnly(top: 5)
                        ],
                      ),
                      SizedBox(
                        width: 160,
                        child: LinearProgressIndicator(
                          minHeight: 2,
                          value: player.slidePosition/player.duration,
                          valueColor: const AlwaysStoppedAnimation<Color>(Colours.main),
                          backgroundColor: Colours.white.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(13.5),
                        ),
                      )
                    ],
                  )
              ),
            ),
          Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              _buildTopBar(context),
              _buildBottomBar(context),
            ],
          ),
          if(player.status == PlayStatus.idle || player.status == PlayStatus.completion)
            Center(
                child: GestureDetector(
                    onTap: _playOrPause,
                    child: Image.asset(
                        Utils.getImgPath('video_play.png'),
                        width: 50,height: 50
                    )
                )
            )
        ],
      ),
    );
  }

  Widget slider(){
    return SliderTheme(
      data: SliderTheme.of(context).copyWith(
        trackHeight: 2,
        trackShape: const RoundedRectSliderTrackShape(),
        activeTrackColor: Colours.main,
        inactiveTrackColor: Colours.white.withOpacity(0.25),
        thumbColor: Colours.white,
        thumbShape: const RoundSliderThumbShape(
            enabledThumbRadius: 6
        ),
        overlayShape: const RoundSliderOverlayShape(
            overlayRadius: 6
        ),
        overlayColor: Colours.white.withOpacity(0.5),
      ),
      child: Slider(
        value: player.startSlide?player.slidePosition:player.currentPosition.toDouble(),
        max: player.duration.toDouble(),
        allowedInteraction: SliderInteraction.tapAndSlide,
        onChangeStart: (value){
          player.startSlide = true;
          player.onSlide = true;
          player.slidePosition = value;
        },
        onChanged: (value)=> player.slidePosition = value,
        onChangeEnd: (value)=> player.setPosition(),
      ),
    );
  }
}